﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UdrinkWater_Project.Officer
{
    public partial class Stock : System.Web.UI.Page
    {
        string Connection = ConfigurationManager.ConnectionStrings["DB_Udrink"].ConnectionString;
        StockDataClassDataContext db = new StockDataClassDataContext();
        public static int dtConut = 0;
        DateTime Stock_Date_ID = DateTime.Now;
        public static DataTable dtStockList = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                dtStockList = new DataTable();
                string T1 = Stock_Date_ID.ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                string T2 = Stock_Date_ID.ToString("HH:mm:ss", new System.Globalization.CultureInfo("en-US"));
                txtStockDate.Text = T1 + " " + T2;
            }
            else
            {

            }
        }

        protected void ASPxGridView4_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            DataTable DataPro = new DataTable();
            DataTable InStock = new DataTable();
            DataTable OutStock = new DataTable();
            if (e.CommandArgs.CommandName == "Cmd_Select")
            {
                string Id = e.CommandArgs.CommandArgument.ToString();
                DataPro = GetDetialPro(Id);
                InStock = GetInstock(Id);
                OutStock = GetOutstock(Id);
                int NumIN = 0;
                int NumOUT = 0;
                for (int i = 0; i < InStock.Rows.Count; i++)
                {

                    NumIN = NumIN + Convert.ToInt32(InStock.Rows[i]["Product_Count"].ToString());
                }
                for (int i = 0; i < OutStock.Rows.Count; i++)
                {
                    NumOUT = NumOUT + Convert.ToInt32(OutStock.Rows[i]["Product_Count"].ToString());
                }
                txtProductId.Text = DataPro.Rows[0]["Product_ID"].ToString();
                txtProductName.Text = DataPro.Rows[0]["Product_name"].ToString();
                txtInStock.Text = (NumIN - NumOUT).ToString();
                txtUnit.Text = DataPro.Rows[0]["Unit_Name"].ToString();

                cnbCatTarnf.Focus();
            }
        }
        private DataTable GetInstock(string Product_ID)
        {
            string sqltext = @"SELECT        Product_ID, Product_Count
                               FROM          TB_StockProductIN
                               WHERE         Product_ID = '" + Product_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }

        private DataTable GetOutstock(string Product_ID)
        {
            string sqltext = @"SELECT        Product_ID, Product_Count
                               FROM          TB_StockProductOUT
                               WHERE         Product_ID = '" + Product_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        private DataTable GetDetialPro(string Product_ID)
        {
            string sqltext = @"SELECT TB_Product.Product_ID, TB_Product.Product_name, TB_Unit_Category.Unit_Name, 
                               TB_Product.Price, TB_Product.In_Stock, TB_Product.Image_Path 
                               FROM TB_Product LEFT JOIN TB_Unit_Category ON TB_Product.Unit = TB_Unit_Category.Unit_ID
                               WHERE TB_Product.Product_ID ='" + Product_ID + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }

        protected void ASPxGridView2_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            DataTable DataEmp = new DataTable();
            if (e.CommandArgs.CommandName == "Cmd_Select")
            {
                string Id = e.CommandArgs.CommandArgument.ToString();
                DataEmp = GetDetialEmp(Id);
                txtEmpID.Text = DataEmp.Rows[0]["ID_Card"].ToString();
                txtEmpName.Text = DataEmp.Rows[0]["Name"].ToString();
            }
        }
        private DataTable GetDetialEmp(string ID_Card)
        {
            string sqltext = @"SELECT ID_Card,( Prefix + '' + Firstname + ' ' + Lastname ) AS Name FROM TB_Employee
                               WHERE [ID_Card] ='" + ID_Card + "' ";
            SqlConnection sqlconn = new SqlConnection(Connection);
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];

        }
        protected void btAddList_Click(object sender, EventArgs e)
        {
            lbWranList.Visible = false;
            lbWranNotEnoght.Visible = false;
            if (cnbCatTarnf.Value.ToString() == "ออกคลัง" && (Convert.ToInt32(txtCount.Text)) - (Convert.ToInt32(txtInStock.Text)) > 0)
            {
                lbWranNotEnoght.Visible = true;
            }
            else
            {
                if (dtStockList != null && dtStockList.Rows.Count == 0)
                {
                    DataRow drStockRow = null;
                    if (dtConut == 0)
                    {
                        dtStockList = new DataTable();
                        dtStockList.Columns.Add(new DataColumn("Product_ID", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("Product_Name", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("Unit", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("CatTranf", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("Count", typeof(int)));

                    }
                    else
                    {
                        dtStockList = new DataTable();
                        dtStockList.Columns.Add(new DataColumn("Product_ID", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("Product_Name", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("Unit", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("CatTranf", typeof(string)));
                        dtStockList.Columns.Add(new DataColumn("Count", typeof(int)));

                    }

                    drStockRow = dtStockList.NewRow();
                    drStockRow["Product_ID"] = txtProductId.Text;
                    drStockRow["Product_Name"] = txtProductName.Text;
                    drStockRow["Unit"] = txtUnit.Text;
                    drStockRow["CatTranf"] = cnbCatTarnf.Value.ToString();
                    drStockRow["Count"] = Int32.Parse(txtCount.Text);

                    dtStockList.Rows.Add(drStockRow);
                    GV_OrderList.DataSource = dtStockList;
                    GV_OrderList.DataBind();
                    dtConut = 1;
                    //Session["TablePrice"] = dtOrderList;
                }
                else if (dtStockList != null && dtStockList.Rows.Count > 0)
                {
                    dtConut = 0;
                    for (int i = 0; i < dtStockList.Rows.Count; i++)
                    {
                        if (dtStockList.Rows[i]["Product_ID"].ToString() == txtProductId.Text && dtStockList.Rows[i]["CatTranf"].ToString() == cnbCatTarnf.Value.ToString())
                        {
                            lbWranList.Visible = true;
                            dtConut = 1;
                        }
                    }
                    if (dtConut != 1)
                    {
                        DataRow drStockRow = dtStockList.NewRow();
                        drStockRow["Product_ID"] = txtProductId.Text;
                        drStockRow["Product_Name"] = txtProductName.Text;
                        drStockRow["Unit"] = txtUnit.Text;
                        drStockRow["CatTranf"] = cnbCatTarnf.Value.ToString();
                        drStockRow["Count"] = Int32.Parse(txtCount.Text);

                        dtStockList.Rows.Add(drStockRow);
                        GV_OrderList.DataSource = dtStockList;
                        GV_OrderList.DataBind();
                        //Session["TablePrice"] = dtOrderList;
                    }

                }
                txtProductId.Text = "";
                txtProductName.Text = "";
                txtInStock.Text = "";
                txtCount.Text = "";
                cnbCatTarnf.Value = "";
                txtUnit.Text = "";
            }




        }

        protected void GV_OrderList_RowCommand(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewRowCommandEventArgs e)
        {
            if (e.CommandArgs.CommandName == "Cmd_Delete")
            {
                // Response.Redirect("PromotionLogin.aspx");
                string Index = e.CommandArgs.CommandArgument.ToString();
                DataTable dt = dtStockList;
                dt.Rows[Convert.ToInt32(Index)].Delete();
                GV_OrderList.DataSource = dt;
                GV_OrderList.DataBind();
            }
        }

        protected void btSaveAndReport_Click(object sender, EventArgs e)
        { 
            lbWarnEmp.Visible = false;
            DataTable FindEmp;
            FindEmp = GetDetialEmp(txtEmpID.Text);
            if (txtEmpID.Text == "" || FindEmp.Rows.Count == 0)
            {
                lbWarnEmp.Visible = true;
                return;
            }
            if (dtStockList != null && dtStockList.Rows.Count > 0)
            {
                
                if (txtEmpID.Text == "" || FindEmp.Rows.Count == 0)
                {
                    lbWarnEmp.Visible = true;
                    return;
                }
                else
                {
                    DataTable dt = new DataTable();
                    dt = dtStockList;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["CatTranf"].ToString() == "เข้าคลัง")
                        {
                            TB_StockProductIN stIn = new TB_StockProductIN();
                            stIn.Product_Date = Stock_Date_ID;
                            stIn.Product_ID = dt.Rows[i]["Product_ID"].ToString();
                            stIn.Product_Count = Convert.ToInt32(dt.Rows[i]["Count"].ToString());
                            stIn.Act_Officer = txtEmpID.Text;
                            db.TB_StockProductINs.InsertOnSubmit(stIn);
                            db.SubmitChanges();
                        }
                        else
                        {
                            TB_StockProductOUT stOut = new TB_StockProductOUT();
                            stOut.Product_Date = Stock_Date_ID;
                            stOut.Product_ID = dt.Rows[i]["Product_ID"].ToString();
                            stOut.Product_Count = Convert.ToInt32(dt.Rows[i]["Count"].ToString());
                            stOut.Act_Officer = txtEmpID.Text;
                            db.TB_StockProductOUTs.InsertOnSubmit(stOut);
                            db.SubmitChanges();
                        }
                    }
                    
                    
                    string T1 = Stock_Date_ID.ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));
                    string T2 = Stock_Date_ID.ToString("HH:mm:ss.fff", new System.Globalization.CultureInfo("en-US"));
                    Session["list"] = (dtStockList.Rows.Count).ToString();
                    Session["StockDateID"] = T1 +" "+ T2;
                    Response.Write("<script>alert('บันทึกรายการเรียบร้อยแล้ว!');</script>");
                    Response.Redirect("StockReport.aspx");
                    
                }
                
            }
        }

        protected void btEmpSert_Click(object sender, EventArgs e)
        {
           
        }

        protected void btProductSert_Click(object sender, EventArgs e)
        {

        }

        protected void btNewOrder_Click(object sender, EventArgs e)
        {
            dtStockList = new DataTable();
            Response.Redirect("Stock.aspx");
        }

        protected void GV_OrderList_SummaryDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewSummaryDisplayTextEventArgs e)
        {

        }

        protected void GV_OrderList_FocusedRowChanged(object sender, EventArgs e)
        {

        }
    }
}